package team.yidong.fenda.serviceImpl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.yidong.fenda.entity.HospitalField;
import team.yidong.fenda.entity.HospitalModule;
import team.yidong.fenda.repository.HospitalModuleRepository;
import team.yidong.fenda.service.HospitalModuleService;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuanlong on 2018/5/28.
 */
@Service
public class HospitalModuleServiceImpl implements HospitalModuleService {
    @Autowired
    HospitalModuleRepository hospitalModuleRepository;

    @Override
    public JSONArray findByHospitalId(Integer hospitalId) {
        List<HospitalModule> hospitalModuleList = hospitalModuleRepository.findByHospitalId(hospitalId);
        JSONArray jsonArray = JSONArray.fromObject(hospitalModuleList);
        return jsonArray;
    }

    @Override
    public JSONArray searchByHospitalId(Integer hospitalId) {

        List<HospitalModule> hospitalModuleList = hospitalModuleRepository.findAll(new Specification<HospitalModule>() {


            @Override
            public Predicate toPredicate(Root<HospitalModule> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (hospitalId != null && !hospitalId.equals("")) {

                    Predicate p = criteriaBuilder.equal(root.get("hospitalId"), hospitalId);
                    predicateList.add(p);
                }
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        });
        return JSONArray.fromObject(hospitalModuleList);
    }

    @Transactional
    @Override
    public void updateIcon(Integer iconId, String iconPath) {
        HospitalModule hospitalModule = hospitalModuleRepository.findOne(iconId);
        hospitalModule.setIcon("https://qny.liuxuanlong.xyz/" + iconPath);
        hospitalModuleRepository.save(hospitalModule);
    }

    @Override
    public void updateHospitalModule(String jsonData) {
        JSONObject jsonObject = JSONObject.fromObject(jsonData);
        HospitalModule hospitalModule = (HospitalModule) JSONObject.toBean(jsonObject, HospitalModule.class);
        hospitalModuleRepository.save(hospitalModule);
    }
}
